package com.xperblueray.stepbystep.controller;

import com.xperblueray.stepbystep.exception.BusinessException;
import com.xperblueray.stepbystep.model.SysDict;
import com.xperblueray.stepbystep.service.SysDictService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

import static com.xperblueray.stepbystep.constant.Constant.ALL_ATTR;

@Controller
@RequestMapping("sysDict")
public class SysDictController {
    Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    SysDictService sysDictService;

    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping("/retry/{name}/{type}")
    @ResponseBody
    public SysDict retryTest(@PathVariable(value = "name") String name, @PathVariable(value = "type") String type) {
        return sysDictService.findByNameAndType(name, type);
    }

    @RequestMapping("/test")
    public String test(Model model) {
        // 查询数据库所有用户
        List<SysDict> sysDicts = sysDictService.findAll();
        model.addAttribute("attr", sysDicts);
        return "sysDict";
    }


    @RequestMapping("/testException")
    public String testGlobalExceptionHandler(Model model) {
        // 查询数据库所有用户
        List<SysDict> sysDicts = sysDictService.findAll();
        model.addAttribute("attr", sysDicts);
        throw new BusinessException("业务异常");
    }

    @RequestMapping("/getDictByNameAndValue/{name}/{value}")
    @ResponseBody
    public SysDict getDictByNameAndValue(@PathVariable("name") String name, @PathVariable("value") String value) {
        return sysDictService.findByNameAndValue(name, value);
    }


    @RequestMapping("/testRedisLoad")
    @ResponseBody
    public SysDict testRedisLoad(Model model) {
        SysDict sys_dict = new SysDict();
        sys_dict.setId("10");
        sys_dict.setName("民族");
        sys_dict.setType("nation");
        sys_dict.setCode("6");
        sys_dict.setValue("白");
        sys_dict.setOrderNum(10);
        sys_dict.setDelFlag(0);
        sysDictService.save(sys_dict);

        List<SysDict> listBeforeLoad = redisTemplate.opsForList().range(ALL_ATTR, 0, -1);
        logger.info(listBeforeLoad.toString());
        SysDict info = sysDictService.findById("10");
        List<SysDict> listAfterLoad = redisTemplate.opsForList().range(ALL_ATTR, 0, -1);
        logger.info(info);
        return info;
    }
}
